var userPic;
var falg = true;
$(function () {
    /*修改上传图片*/
    $('#userPhotoBox').show();
    $('#userPhotoDetails').hide();
    uploadUserPhoto();
});

function checkCoords() {
    //判断是否有裁剪
    if (parseInt($('#w').val())) {
        var loading = ZZHT.msg('图像处理中，请稍候...', {icon: 16, shade: [0.3, '#999999']});
        /*获取裁剪数据*/
        var photoData = {};
        photoData.x = $('#x').val();
        photoData.y = $('#y').val();
        photoData.w = $('#w').val();
        photoData.h = $('#h').val();
        photoData.photoSrc = $('#photoSrc').val();
        console.log(photoData);
        
        //获取到裁剪后的img
        
//      $.post('http://test.izzht.cn/Home/users/editUserPhoto', photoData, function (data, textStatus) {
//      	console.log(data);
//          if (data.status == 1) {
//              //将上传的图片路径赋给全局变量
//              userPic = data.data;
//              $('#userPhotoPreview').html('<img id="userPhoto" class="ipt" src="' +userPic+ '"  height="150" />');
//              $('#userPhotoPreview1').html('<img id="userPhoto1" class="ipt" src="' + userPic + '"  height="150" />');
//              $('#userPhotoCut').hide();
//              $('#userPhoto').show();
////              location.href='4.html';
//          } else {
//              ZZHT.msg(data.msg, {icon: 2});
//              return false;
//          }
//      });
        return true;
    }
    ZZHT.msg('请对图片裁剪后再进行提交', {icon: 2});
    return false;
}

function returnPhotoPage() {
    window.location.reload();
}

function uploadUserPhoto() {
    ZZHT.upload({
        pick: '#userPhotoPicker',
        formData: {dir: 'users', isWatermark: 1, isThumb: 1},
        accept: {extensions: 'gif,jpg,jpeg,bmp,png', mimeTypes: 'image/*'},
        compress:{
            width:383,
            height:383,
            // 如果发现压缩后文件大小比原来还大，则使用原来图片
            // 此属性可能会影响图片自动纠正功能
            noCompressIfLarger: false,

            // 单位字节，如果图片大小小于此值，不会采用压缩。
            compressSize:5120
        },
        callback: function (f) {
//          var json = ZZHT.toJson(f);
            console.log(f);
            var json = f.entity;
//          if (json.status == 1) {
                /*上传成功*/
                $('#userPhotoCut').show();
                $('#userPhoto').hide();

                var uploadPhotoSrc = json;

                var cutCode = '<img src="' + uploadPhotoSrc + '" id="target" alt="" style="max-width:606;height:auto;" />';
                cutCode += '<div id="preview-pane">';
                cutCode += '<div><p align="center">裁剪预览</p>';
                cutCode += '<div class="cut-help"><h4>操作帮助</h4>'
                cutCode += '<p>请在裁剪区域放大缩小及移动选取框，选择要裁剪的范围，裁切宽高比例固定；裁切后的效果为右侧预览图所显示；保存提交后生效。</p></div></div>'
                cutCode += '<div class="preview-container"><img src="' + uploadPhotoSrc + '"  class="jcrop-preview"  alt="Preview" /></div></div>';
                $('#userPhotoCutBox>p').html(cutCode);
                $('#photoSrc').val(uploadPhotoSrc);
                $('#userPic').val(uploadPhotoSrc);
                //初始化jcrop
                jcropInit();
                $('#uploadMsg').empty().hide();
//          } else {
//              ZZHT.msg(json.msg, {icon: 2});
//          }
        },
        progress: function (rate) {
            $('#uploadMsg').show().html('已上传' + rate + "%");
        }
    });
}

var jcrop_api;

function jcropInit() {
    var boundx,
        boundy,

        $preview = $('#preview-pane'),
        $pcnt = $('#preview-pane .preview-container'),
        $pimg = $('#preview-pane .preview-container img'),

        xsize = $pcnt.width(),
        ysize = $pcnt.height();

    $('#target').Jcrop({
        onChange: updatePreview,
        onSelect: updatePreview,
        aspectRatio: 1,
    }, function () {
        // Use the API to get the real image size
        var bounds = this.getBounds();
        boundx = bounds[0];
        boundy = bounds[1];
        //设置宽度以使文字居中
        $('#img-src').css('width', boundx + 'px');

        // Store the API in the jcrop_api variable
        jcrop_api = this;
        jcrop_api.setSelect([0, 0, 150, 150]);

        // Move the preview into the jcrop container for css positioning
        $preview.appendTo(jcrop_api.ui.holder);
    });

    function updatePreview(c) {
        if (parseInt(c.w) > 0) {
            var rx = xsize / c.w;
            var ry = ysize / c.h;

            $pimg.css({
                width: Math.round(rx * boundx) + 'px',
                height: Math.round(ry * boundy) + 'px',
                marginLeft: '-' + Math.round(rx * c.x) + 'px',
                marginTop: '-' + Math.round(ry * c.y) + 'px'
            });
        }
        //设置裁剪的图片数据
        $('#x').val(c.x);
        $('#y').val(c.y);
        $('#w').val(c.w);
        $('#h').val(c.h);
    };
}


$(function () {
    /* 表单验证 */
    $('#userEditForm').validator({
        fields: {
//          userName: {rule: "required", msg: {required: "输入内容不能为空"}, tip: "支持字母、数字、中文3-20个字符"},
//          userSex: {rule: "checked;", msg: {checked: "至少选择一项"}, tip: "请选择您的性别"}
        },
        valid: function (form) {
            var params = ZZHT.getParams('.ipt');
            if (!userPic) {
                userPic = $('#userPic').val();
            }
            //接收上传的头像路径
            params.userPhoto = userPic;
            params.userId = localStorage.userId;
            console.log(params);
            var loading = ZZHT.msg('正在提交数据，请稍后...', {icon: 16, time: 60000});
            $.post(SURL+'users/update', params, function (data, textStatus) {
                layer.close(loading);
                console.log(data);
//              if (json.status == '1') {
//                  ZZHT.msg("操作成功", {icon: 1});
//                  return;
//              } else {
//                  ZZHT.msg(json.msg, {icon: 2});
//              }
            });
			
        },

    });

});